package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.article.service.MessageHandler;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.ApArticleConScore;
import com.heima.model.message.ArticleVisitStreamMess;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MessageHandlerImpl implements MessageHandler {

    @Autowired
    private ApArticleServiceImpl apArticleService;
    @Autowired
    private CacheService cacheService;

    @Override
    public void RealTimeArtHotMessageHandler(String realHotMess) {
        ArticleVisitStreamMess articleVisitStreamMess = JSON.parseObject(realHotMess, ArticleVisitStreamMess.class);

        log.info("实时热点数据：" + articleVisitStreamMess);
        // 更新数据库
        ApArticle apArticle = new ApArticle();
        apArticle.setId(articleVisitStreamMess.getArticleId());
        apArticle.setLikes(articleVisitStreamMess.getLike());
        apArticle.setCollection(articleVisitStreamMess.getCollect());
        apArticle.setComment(articleVisitStreamMess.getComment());
        apArticle.setViews(articleVisitStreamMess.getView());
        log.info("apArticle:" + apArticle);
        apArticleService.updateById(apArticle);

        // 实时处理分值
        ApArticle apArticleDB = apArticleService.getById(articleVisitStreamMess.getArticleId());
        log.info("apArticleDB:"+apArticleDB);

        if ( apArticleDB != null) {
            ApArticleConScore apArticleConScore = HotNewsServiceImpl.getApArticleConScore(apArticleDB);


            // 更新缓存
                //更新频道缓存
            updateCache(apArticleConScore, String.valueOf(apArticleConScore.getChannelId()));
                //更新全部缓存
            updateCache(apArticleConScore, ArticleConstants.DEFAULT_TAG);

        }


    }

    private void updateCache(ApArticleConScore apArticleConScore, String channelId) {
        boolean flag = true; // true则不存在数据在缓存，false则存在
        String string = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + channelId);
        if ( StringUtils.isNotBlank(string)) {
            List<ApArticleConScore> apArticleConScoreList = JSON.parseArray(string, ApArticleConScore.class);
            for (ApArticleConScore item : apArticleConScoreList) {
                //是否存在与缓存，存在设置新分值
                if (item.getId().equals(apArticleConScore.getId())) {
                    item.setScore(apArticleConScore.getScore());
                    flag = false;
                    break;
                }
            }
            //不存在于缓存， 少于30条数据直接添加，
            if (flag) {
                if (apArticleConScoreList.size() < 30){
                    apArticleConScoreList.add(apArticleConScore);

                }else {
                    //否者替换
                    apArticleConScoreList.sort(Comparator.comparingInt(ApArticleConScore::getScore).reversed());
                    if (apArticleConScore.getScore() >= apArticleConScoreList.get(0).getScore()) {
                        apArticleConScoreList.remove(0);
                        apArticleConScoreList.add(apArticleConScore);
                    }

                }
            }
            apArticleConScoreList.sort(Comparator.comparingInt(ApArticleConScore::getScore).reversed());
            cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + channelId, JSON.toJSONString(apArticleConScoreList));
        }
    }
}
